// API工具函数
import store from '@/store'

// 格式化请求参数
export const formatParams = (params) => {
  const formatted = {}
  Object.keys(params).forEach(key => {
    const value = params[key]
    if (value !== null && value !== undefined && value !== '') {
      formatted[key] = value
    }
  })
  return formatted
}

// 构建查询字符串
export const buildQueryString = (params) => {
  const query = formatParams(params)
  return Object.keys(query)
    .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(query[key])}`)
    .join('&')
}

// 处理API响应数据
export const handleResponse = (response) => {
  if (response.code === 200) {
    return response.data
  } else {
    throw new Error(response.message || '请求失败')
  }
}

// 处理API错误
export const handleError = (error) => {
  console.error('API Error:', error)
  
  let message = '网络请求失败'
  if (error.message) {
    message = error.message
  } else if (error.errMsg) {
    message = error.errMsg
  }
  
  uni.showToast({
    title: message,
    icon: 'none'
  })
  
  return Promise.reject(error)
}

// 添加请求loading
export const showLoading = (title = '加载中...') => {
  uni.showLoading({
    title,
    mask: true
  })
}

// 隐藏请求loading
export const hideLoading = () => {
  uni.hideLoading()
}

// 检查网络状态
export const checkNetwork = () => {
  return new Promise((resolve) => {
    uni.getNetworkType({
      success: (res) => {
        if (res.networkType === 'none') {
          uni.showToast({
            title: '网络连接失败，请检查网络设置',
            icon: 'none'
          })
          resolve(false)
        } else {
          resolve(true)
        }
      },
      fail: () => {
        resolve(false)
      }
    })
  })
}

// 获取设备信息
export const getDeviceInfo = () => {
  return new Promise((resolve) => {
    uni.getSystemInfo({
      success: (res) => {
        resolve(res)
      },
      fail: () => {
        resolve({})
      }
    })
  })
}

// 缓存管理
export const cache = {
  // 设置缓存
  set(key, data, expire = 0) {
    const cacheData = {
      data,
      expire: expire > 0 ? Date.now() + expire : 0
    }
    uni.setStorageSync(key, JSON.stringify(cacheData))
  },
  
  // 获取缓存
  get(key) {
    try {
      const cacheStr = uni.getStorageSync(key)
      if (!cacheStr) return null
      
      const cacheData = JSON.parse(cacheStr)
      if (cacheData.expire > 0 && Date.now() > cacheData.expire) {
        this.remove(key)
        return null
      }
      
      return cacheData.data
    } catch (error) {
      return null
    }
  },
  
  // 删除缓存
  remove(key) {
    uni.removeStorageSync(key)
  },
  
  // 清空缓存
  clear() {
    uni.clearStorageSync()
  }
}

// 防抖函数
export const debounce = (func, wait = 300) => {
  let timeout
  return function executedFunction(...args) {
    const later = () => {
      clearTimeout(timeout)
      func(...args)
    }
    clearTimeout(timeout)
    timeout = setTimeout(later, wait)
  }
}

// 节流函数
export const throttle = (func, limit = 300) => {
  let inThrottle
  return function executedFunction(...args) {
    if (!inThrottle) {
      func.apply(this, args)
      inThrottle = true
      setTimeout(() => inThrottle = false, limit)
    }
  }
}

// 格式化文件大小
export const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 验证文件类型
export const validateFileType = (file, allowedTypes) => {
  if (!allowedTypes || allowedTypes.length === 0) return true
  return allowedTypes.includes(file.type)
}

// 验证文件大小
export const validateFileSize = (file, maxSize) => {
  if (!maxSize) return true
  return file.size <= maxSize
}

// 生成唯一ID
export const generateId = () => {
  return Date.now().toString(36) + Math.random().toString(36).substr(2)
}

// 格式化日期
export const formatDate = (date, format = 'YYYY-MM-DD HH:mm:ss') => {
  const d = new Date(date)
  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  const hours = String(d.getHours()).padStart(2, '0')
  const minutes = String(d.getMinutes()).padStart(2, '0')
  const seconds = String(d.getSeconds()).padStart(2, '0')
  
  return format
    .replace('YYYY', year)
    .replace('MM', month)
    .replace('DD', day)
    .replace('HH', hours)
    .replace('mm', minutes)
    .replace('ss', seconds)
}

// 检查权限
export const checkPermission = (permission) => {
  const userPermissions = store.getters['auth/userPermissions'] || []
  return userPermissions.includes(permission)
}

// 获取用户角色
export const getUserRole = () => {
  return store.getters['auth/userRole'] || 'user'
}

// 检查是否为管理员
export const isAdmin = () => {
  return getUserRole() === 'admin'
} 